package com.example.loginmvvm.player

import android.os.Looper
import android.util.Log
import com.example.loginmvvm.App
import com.example.loginmvvm.lifecycle.*

/*
 * class title: 
 * Author by RenChunLin, Email 18957806320@163.com, Date on 2021/4/19.
 * PS: Not easy to write code, please indicate.
 */

/**
 * 数据容器
 * 可以监听数据的变换
 */
class DataListenContainer<T> {
    private val blocks = arrayListOf<(T?) -> Unit>()
    private val viewLifecycleProviders = hashMapOf<(T?) -> Unit, LifecycleProvide>()

    var value: T? = null
        //当数据变换的时候，就通知更新
        set(value: T?) {
            field=value //赋值
            //判断当前线程是不是主线程
            //如果是，则直接执行，否则切换到主线程再执行
            if (Looper.getMainLooper().thread === Thread.currentThread()) { //是主线程
                blocks.forEach {
                    //判断对应的View的生命周期是什么
                    dispatchValue(it, value)
                }
            } else {  //不是主线程
                App.handler.post {
                    blocks.forEach {
                        //判断对应的View的生命周期是什么
                        dispatchValue(it, value)
                    }
                }
            }
        }

    private fun dispatchValue(it: (T?) -> Unit, value: T?) {
        val viewModelProvider = viewLifecycleProviders[it]
        if (viewModelProvider != null && viewModelProvider.isAtLeast(LifeState.START)) {
            it.invoke(value)
        }
    }

    fun addListener(owner: ILifecycleOwner, valueObserver: (T?) -> Unit) {
        val lifecycleProvider = owner.getLifecycleProvider()
        viewLifecycleProviders[valueObserver] = lifecycleProvider

        //当view destroy的时候，要从集合中删除
        val observerWrapper = ValueObserverWrapper(valueObserver)
        lifecycleProvider.addLifeListener(observerWrapper)

        if (!blocks.contains(valueObserver)) {
            blocks.add(valueObserver)
        }
    }

    inner class ValueObserverWrapper(private val valueObserver: (T?) -> Unit) :
        AbsLifecycle() {

        //当我监听到当前View，生命周期为Destroy的时候，就把LifecycleProvide从集合中删除

        override fun onViewLifeStateChange(state: LifeState) {
            if (state == LifeState.DESTROY) {
                viewLifecycleProviders.remove(valueObserver)
            }
        }

    }
}